<?php
/**
 * API入口文件
 */

// 设置响应头
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');

// 处理预检请求
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// 自动加载类文件
spl_autoload_register(function ($className) {
    $filePath = __DIR__ . '/../classes/' . $className . '.php';
    if (file_exists($filePath)) {
        require_once $filePath;
    }
});

// 加载配置文件
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../helpers/functions.php';

try {
    // 获取请求路径和方法
    $requestUri = $_SERVER['REQUEST_URI'];
    $path = parse_url($requestUri, PHP_URL_PATH);
    
    // 移除API前缀
    $path = str_replace('/api', '', $path);
    
    // 获取请求方法
    $method = $_SERVER['REQUEST_METHOD'];
    
    // 获取请求数据
    $data = [];
    if ($method === 'GET') {
        $data = $_GET;
    } else {
        $input = file_get_contents('php://input');
        if (!empty($input)) {
            $data = json_decode($input, true) ?? $_POST;
        }
    }
    
    // 处理文件上传
    if (!empty($_FILES)) {
        $data = array_merge($data, $_FILES);
    }
    
    // 创建路由实例并处理请求
    $router = new Router();
    $result = $router->handle($path, $method, $data);
    
    // 输出结果
    echo json_encode($result, JSON_UNESCAPED_UNICODE);
    
} catch (Exception $e) {
    // 错误处理
    $errorResponse = apiError($e->getMessage(), 500);
    
    // 记录错误日志
    logMessage("API Error: " . $e->getMessage() . " at " . $e->getFile() . ":" . $e->getLine(), 'ERROR');
    
    echo json_encode($errorResponse, JSON_UNESCAPED_UNICODE);
}

?>